//
//  CSSOAuthViewController.swift
//  weibo28
//
//  Created by chushushan on 16/5/12.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking


//微博的appkey
let WeiboAppKey = "3924687344"

//授权回调页
let WeiboRedirect_Url = "http://www.itcast.com"

//获取accesstoken
let WeiboAppSecret = "9ca205576a94d3b97e2b39f0974a5d50"



class CSSOAuthViewController: UIViewController {

    
    private lazy var webView: UIWebView = UIWebView()
    
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Url)"
        let request = NSURLRequest(URL: NSURL(string: url)!)
        
        webView.loadRequest(request)
        
        setupNavUI()
    }
    
    
    //nav里面的按钮
    private func setupNavUI() {
    
        navigationItem.title = "微博登录"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", fontSize: 15, target: self, action: "autoFillAction")
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", fontSize: 15, target: self, action: "cancelAction")
    
    }
    
    //自动填充按钮的点击事件
    @objc private func autoFillAction() {
        
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = 'shan957108102@163.com'; document.getElementById('passwd').value = 'chushushan911028'")
        
    
    }
    //取消按钮的点击事件
    @objc private func cancelAction() {
    
    dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    
    
 

}


// MARK: - webView的代理方法

extension CSSOAuthViewController: UIWebViewDelegate {

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //加入地址为空就不执行
        guard let url = request.URL else {
        
        return false
        }
        //如果url的绝对路径不是以授权回调页网址为前缀
        if !url.absoluteString.hasPrefix(WeiboRedirect_Url) {
         return true
        }
        
        //判断返回的url有以code=开头的参数
        if let query = url.query where query.hasPrefix("code=") {
            
            let code = query.substringFromIndex("code=".endIndex)
            print(code)
            
            CSSUserAccountViewModel.shareUserAccount.requestAccessToken(code, complete: { (isSuccess) -> () in
                
                if isSuccess {
   
//                print("登录成功")
                    //dismis掉当前控制器
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        //发送通知，让主window切换到欢迎界面
                    NSNotificationCenter.defaultCenter().postNotificationName( SwitchRootVCNotification, object: self)
                        
                    })
                    
                    
                } else {
                    SVProgressHUD.showErrorWithStatus("登录失败")
                }
            })
        } else {
        //取消回调页
            dismissViewControllerAnimated(true, completion: nil)        
        }
 
        return false
    }

    //加载成功时
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    //加载结束的时候
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //加载失败的时候
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }

}







